let express = require('express');
let router = express.Router();
let shoppingAndStarDao = require("../dao/ShoppingAndStarDao");
let pager = require("../util/PagerHelper")

/* GET users listing. */
router.all('/list.do', function(req, res, next) {
    pager.href ="/api/allBuy/list.do";
    let table = "users",
        where = "",
        and = ""
    shoppingAndStarDao.getCount(table,where,and).then(count => {
        pager.setCount(count);
        return shoppingAndStarDao.findBy(table,where,and);
    }).then(data => {
        pager.data = data;
        res.json({
            code:200, //结果编码,200表示成功，404表示未找到
            data:pager
        });
    }).catch(err => next(err));
});



router.get("/edit.do", (req, res, next) => {
    let id = req.query.id;
    let table = "users"
    console.log("id:"+id);
    if (id) {
        shoppingAndStarDao.findById(id,table).then(editObj => {
            if (editObj) {
                res.json({
                    code: 200,
                    data: editObj
                });
            } else {
                res.json({
                    code: 404,
                    msg: "没有找到记录！"
                });
            }
        }).catch(err => next(err));
    } else {
        res.json({
            code: 410,
            msg: "没有id！"
        });
    }
});


router.post("/save.do", (req, res, next) => {
    let newObj = Object.assign({}, req.body);
    let table ="users"
    //区分添加还是编辑
    if (newObj.id) {
        //编辑
        shoppingAndStarDao.update(table,newObj, newObj.id).then(data => res.json({
            code: 200,
            msg: "修改成功"
        })).catch(err => next(err));
    }
});

/*
根据ids插入订单表
 */
router.get("/insert.do",(req,res,next) =>{
    let idsStr = req.query.ids;
    let table1 = "orders";
    let table2 = "users,shoppingcard";
    console.log(idsStr);
    let ids;
    if (Array.isArray(idsStr)){
        ids = idsStr;
    } else {
        ids = idsStr.split(",");
    }
    shoppingAndStarDao.insertByIds(table1,table2, ids).then(data => res.json({
        code: 200,
        msg: "插入成功"
    })).catch(err => next(err));
});

/*
根据ids删除多条数据
 */
router.get("/delBatch.do",(req,res,next) =>{
    let idsStr = req.query.ids;
    let table = "shoppingcard"
    console.log(idsStr);
    let ids;
    if (Array.isArray(idsStr)){
        ids = idsStr;
    } else {
        ids = idsStr.split(",");
    }
    shoppingAndStarDao.deleteByIds(table, ids).then(data => res.json({
        code: 200,
        msg: "删除成功"
    })).catch(err => next(err));
});

module.exports = router;
